<template>
  <div ref="layerAuthorityModal" v-if="visible" class="authority-modal">
    <a-modal :getContainer="() => $refs.layerAuthorityModal" :visible="visible" :title="`【${title}】-文件权限设置`" width="800px" @ok="handleOk" @cancel="handleCancel">
      <BaseCollapse title="管理者" :tooltip="true" :tooltipWidth="'200px'">
        <template #promptTitle>
          <p>
            <span>参与文件管理的成员列表，管理者可以进行移动和删除操作。上级继承的管理者不可被移除。</span>
          </p>
        </template>
        <a-table :pagination="false" :scroll="{ y: 200 }" :columns="columns" :data-source="state.managersData">
          <template #bodyCell="{ column, record }">
            <!-- 用户名称 -->
            <template v-if="column.dataIndex == 'memberName' && record?.canSelectUser">
              <div>
                <a-tree-select
                  style="width: 100%"
                  tree-checkable
                  :dropdownMatchSelectWidth="300"
                  v-model:value="record.memberName"
                  tree-default-expand-all
                  :tree-data="state.treeManagersData"
                  tree-node-filter-prop="label"
                  class="tree-select"
                >
                </a-tree-select>
              </div>
            </template>
            <!-- 权限设置选项 -->
            <template v-if="column.dataIndex == 'permission' && record.memberId !== state.id && !record?.canSelectCollaborators">
              <div>
                <a-select style="width: 100%" :allowClear="false" v-model:value="record.permission" :firstActiveValue="['2']" @select="removeManagers(record)">
                  <a-select-option value="2">全部权限</a-select-option>
                  <a-select-option style="cursor: pointer; color: red; font-weight: 550" value="8" class="remove">移除权限</a-select-option>
                </a-select>
              </div>
            </template>
            <template v-if="column.dataIndex == 'permission' && record.canSelectCollaborators">
              <div>
                <a-select style="width: 100%" :allowClear="false" v-model:value="record.permission" :firstActiveValue="['2']" @select="removeManagers(record)">
                  <a-select-option value="2">全部权限</a-select-option>
                  <a-select-option style="cursor: pointer; color: red; font-weight: 550" value="8" class="remove">移除权限</a-select-option>
                </a-select>
              </div>
            </template>
            <template v-if="column.dataIndex == 'permission' && record.memberId === state.id">
              <span>全部权限</span>
            </template>
          </template>
        </a-table>
        <a-button type="dashed" @click="managersAdd" style="width: 100%">+ 添加</a-button>
      </BaseCollapse>
      <BaseCollapse title="用户" :tooltip="true" :tooltipWidth="'200px'">
        <template #promptTitle>
          <p>
            <span>参与文件协作的成员列表，协作者不能进行移动和删除操作。</span>
          </p>
        </template>
        <a-table :pagination="false" :scroll="{ y: 200 }" :columns="columns" :data-source="state.collaboratorsData">
          <template #bodyCell="{ column, record }">
            <!-- 用户名称 -->
            <template v-if="column.dataIndex == 'memberName' && record?.canSelectUser">
              <div>
                <a-tree-select
                  style="width: 100%"
                  tree-checkable
                  :dropdownMatchSelectWidth="300"
                  v-model:value="record.memberName"
                  tree-default-expand-all
                  :tree-data="state.treeCollaboratorsData"
                  tree-node-filter-prop="label"
                >
                </a-tree-select>
              </div>
            </template>
            <!-- 权限设置选项 -->
            <template v-if="column.dataIndex == 'permission'">
              <div>
                <a-select style="width: 100%" :allowClear="false" v-model:value="record.permission" :firstActiveValue="['3']" @select="removeCollaborators(record)">
                  <a-select-option value="3">上传/下载</a-select-option>
                  <a-select-option value="4">仅预览</a-select-option>
                  <a-select-option value="5">仅上传</a-select-option>
                  <a-select-option value="6">仅下载</a-select-option>
                  <a-select-option style="cursor: pointer; color: red; font-weight: 550" class="remove" value="7">移除权限</a-select-option>
                </a-select>
              </div>
            </template>
          </template>
        </a-table>
        <a-button type="dashed" @click="collaboratorsAdd" style="width: 100%">+ 添加</a-button>
      </BaseCollapse>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import { getPermission, savePermission } from '@/config/api/deptFile';
import { orgTreeDataSubject } from '@/config/api/system';
import { message } from 'ant-design-vue';
import { getTreeData } from '@/utils/dictionary';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  directoryId: {
    type: String,
    default: null
  },
  title: {
    type: String,
    default: ''
  }
});
const emit = defineEmits(['update:visible']);
const userInfo = window.localStorage.getItem('LOGIN__INFO__');
const state = reactive({
  id: JSON.parse(userInfo).id, // 登录用户的id
  treeManagersData: [], // 管理者机构树
  treeCollaboratorsData: [], // 协作者机构树
  treeSublevel: {
    nameKey: 'name',
    nameValue: 'id',
    nameChildren: 'childOrg',
    childrenLevel: {
      nameKey: 'nickName',
      nameValue: 'id',
      nameChildren: 'subjectSimpleList'
    }
  }, // 过滤所需的层级替换字段
  managersData: [], //管理者数据
  collaboratorsData: [] // 协作者数据
});

const columns = [
  { title: '名称', dataIndex: 'memberName', key: 'memberName', width: 120 },
  { title: '联系方式', dataIndex: 'memberPhone', key: 'memberPhone', width: 120 },
  { title: '权限', dataIndex: 'permission', key: 'permission', width: 120 }
];

// 初始化赋值
getViewData();
function getViewData() {
  Promise.all([getPermission(props.directoryId), orgTreeDataSubject({ pageSize: 500 })]).then(([getDataRes, getTreeDataRes]) => {
    const res = getDataRes.data;
    res.forEach((item) => {
      if (item.permission == 2) {
        state.managersData.push(item);
      } else {
        state.collaboratorsData.push(item);
      }
    });
    getSubjectTree([filterTree({ label: '全部', value: -1, children: getTreeData(getTreeDataRes.data, state.treeSublevel) })]);
  });
}

// // 过滤树数据
// function filterTreeData(list: any) {
//   if (list?.length === 0 || !list) return false;
//   list.map((item: any) => {
//     if (Array.isArray(item.childOrg) && item.subjectSimpleList?.length > 0) {
//       item.subjectSimpleList.map((val: any) => {
//         item.childOrg.push({ ...val, name: val.nickName });
//       });
//     }
//     filterTreeData(item.childOrg);
//   });
//   return list;
// }

// 过滤树节点
const filterTree = (tmp) => {
  if (tmp.id === -1) {
    tmp.class = 'disable';
  }
  return tmp;
};

// 管理者添加
let temp: any = ref(2);
const managersAdd = () => {
  state.managersData.push({
    memberName: [],
    memberPhone: '---------',
    permission: null,
    temp: temp.value++,
    canSelectUser: true,
    canSelectCollaborators: true
  });
};

// 协作者添加
const collaboratorsAdd = () => {
  state.collaboratorsData.push({
    memberName: [],
    memberPhone: '---------',
    permission: null,
    temp: temp.value++,
    canSelectUser: true,
    canSelectCollaborators: true
  });
};

// 管理者移除权限
const removeManagers = (record) => {
  if (record.permission == 8) {
    if (record.temp) {
      state.managersData = state.managersData.filter((item) => item.temp !== record.temp);
    } else {
      state.managersData = state.managersData.filter((item) => item.memberId !== record.memberId);
    }
  }
};

// 协作者移除
const removeCollaborators = (record) => {
  if (record.permission == 7) {
    if (record.temp) {
      state.collaboratorsData = state.collaboratorsData.filter((item) => item.temp !== record.temp);
    } else {
      state.collaboratorsData = state.collaboratorsData.filter((item) => item.memberId !== record.memberId);
    }
  }
};

// 用户机构树
function getSubjectTree(result) {
  // state.treeManagersData = result;
  // if (!state.managersData.every((item) => item?.isInherit == 0)) {
  //   state.managersData.forEach((item) => {
  //     if (item?.isInherit === 1) {
  //       state.treeCollaboratorsData = AddDisableAttributes(result, item.memberId, true);
  //     }
  //   });
  // } else {
  //   state.treeCollaboratorsData = result;
  // }
  state.managersData.forEach((item) => {
    state.treeCollaboratorsData = AddDisableAttributes(result, item.memberId, true);
  });
  state.collaboratorsData.forEach((item) => {
    state.treeManagersData = AddDisableAttributes(result, item.memberId, true);
  });
}

// 选中管理者或协作者时过滤对方的用户
// function filterManagersOrCollaborators() {
//   state.managersData.forEach((item) => {
//     state.treeCollaboratorsData = AddDisableAttributes(result, item.memberId, true);
//   });
//   state.collaboratorsData.forEach((item) => {
//     state.treeManagersData = AddDisableAttributes(result, item.memberId, true);
//   });
// }

// 递归添加禁用属性
function AddDisableAttributes(treeData, id, boolean) {
  if (treeData[0].value === id) {
    treeData[0].disableCheckbox = boolean;
    return treeData;
  }
  const searchId = (source, id) => {
    for (let i = 0; i < source.length; i++) {
      const item = source[i];
      if (item.value === id) {
        item.disableCheckbox = boolean;
        return;
      }
      if (item.children) {
        searchId(item.children, id);
      }
    }
  };
  searchId(treeData[0].children, id);
  return treeData;
}
// 保存权限设置
const handleOk = async () => {
  console.log(state.managersData, 555);
  console.log(state.collaboratorsData, 666);
  let params = [...state.managersData, ...state.collaboratorsData];
  params = params.filter((item) => item.isInherit !== 1);
  params.forEach((item) => {
    item.directoryId = props.directoryId;
    if (item.canSelectUser && item.canSelectCollaborators) {
      item.memberIds = item.memberName.join(',');
      delete item.memberName, item.memberPhone;
    } else {
      item.memberIds = item.memberId;
      delete item.memberId;
    }
  });
  savePermission(props.directoryId, params).then((result) => {
    if (result.success) {
      message.success('设置成功');
      emit('update:visible', false);
    }
  });
};
// 取消弹窗
const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<style scoped lang="less">
:deep(.ant-table-content) {
  max-height: 200px;
  overflow-y: scroll;
}
/deep/ .ant-table-thead > tr > th {
  font-weight: 700 !important;
  background-color: #e5eefd !important;
}
.authority-modal {
  .disable {
    display: none !important;
  }
}

/deep/.ant-modal-body:nth-child(1) {
  margin-bottom: 20px;
}
.remove:hover {
  font-weight: bold !important;
}
</style>
